package app

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

// Route 根据url进行路由的数据结构体
type Route struct {
	Name        string           //描述该url对应的操作的名字，没有什么额外作用
	Method      string           //描述该url对应的操作，尽量是get / post
	Pattern     string           //对应的url
	HandlerFunc http.HandlerFunc //对应的操作函数
}

// Routes 一个路由链接的序列
type Routes []Route

// NewRouter 创建新的Router
func NewRouter() *mux.Router {
	router := mux.NewRouter().StrictSlash(true)
	for _, route := range routes {
		var handler http.Handler
		handler = route.HandlerFunc
		handler = Logger(handler, route.Name)
		router.
			Methods(route.Method).
			Path(route.Pattern).
			Name(route.Name).
			Handler(handler)
	}
	return router
}

// Index 首页请求，用于测试
func Index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello World!")
}

var routes = Routes{
	//一个用于测试的Route
	Route{
		"Index",
		"GET",
		"/",
		Index,
	},
	Route{
		"Hello",
		"GET",
		"/hello",
		apihello,
	},
	Route{
		"根据名称获取地址",
		"GET",
		"/add2name/{address}",
		getnamefromadd,
	},
	Route{
		"根据地址获得名称",
		"GET",
		"/name2add/{name}",
		getaddfromname,
	},
	Route{
		"获取账户余额",
		"GET",
		"/bank/getinfo/{Name}",
		bankgetinfo,
	},
	Route{
		"取款",
		"POST",
		"/bank/decreaseMoney",
		decreaseMoney,
	},
	Route{
		"存款",
		"POST",
		"/bank/increaseMoney",
		increaseMoney,
	},
	Route{
		"发起交易",
		"POST",
		"/transaction/post",
		createtransaction,
	},
	Route{
		"获取债权信息",
		"GET",
		"/debt/getdebt/{Name}",
		debtgetinfo,
	},
	Route{
		"转移债权",
		"POST",
		"/debt/transfer",
		debtTransfer,
	},
	Route{
		"银行融资",
		"POST",
		"/debt/bankhelp",
		debtbankhelp,
	},
	Route{
		"支付债务",
		"POST",
		"/debt/pay",
		debtpay,
	},
	Route{
		"还银行钱",
		"POST",
		"/debt/paybank",
		paybank,
	},
}
